<template>
  <el-card shadow="always">
    <el-pagination
      @size-change="handleSizeChange"
      slot="header"
      :page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      :layout="paginationLayout"
      :current-page.sync="currentPage"
      :total="documents.length"
    ></el-pagination>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      row-key="id"
      ref="documentList"
      id="documentList"
      highlight-current-row
      size="mini">
      <el-table-column
        v-if="true"
        label="ID"
        prop="id"
        width="60"
        align="center"
        header-align="center"
      ></el-table-column>
      <el-table-column
        label="名称"
        prop="name"
        align="center"
        header-align="center"
        sortable>
        <div slot-scope="scope">{{ compress(scope.row.name) }}</div>
      </el-table-column>
      <el-table-column
        label="最后修改时间"
        prop="updateTime"
        align="center"
        width="100"
        header-align="center"
        sortable>
        <div slot-scope="scope">{{ compressDate(scope.row.updateTime) }}</div>
      </el-table-column>
      <el-table-column
        label="操作"
        header-align="center"
        align="left">
        <div slot-scope="scope">
          <el-popover disabled>
            <el-button slot="reference" icon="el-icon-search" title="查看日志" size="small" @click="rowSelect(scope.row)" circle></el-button>
          </el-popover>
          <el-popover disabled>
            <el-button slot="reference" icon="el-icon-edit" title="编辑文档" type="primary" size="small" @click="editDoc(scope.row)" circle></el-button>
          </el-popover>
          <el-popconfirm confirm-button-text="删除" cancel-button-text="取消" :title="'确认删除文档 ' + scope.row.name + ' 吗？'" @onConfirm="deleteDoc(scope.row)">
            <el-button v-if="hasPermission(scope.row.creatorId)" slot="reference" icon="el-icon-delete" title="删除文档" size="small" type="danger" circle></el-button>
          </el-popconfirm>
          <el-popover disabled>
            <el-button slot="reference" v-if="scope.row.url" icon="el-icon-link" title="去发布页" size="small" type="success" @click="goPublishPage(scope.row)" circle></el-button>
          </el-popover>
          <el-popover
            v-model="visible.publish[scope.$index]"
            placement="bottom">
            <el-button v-if="!scope.row.url && hasPermission(scope.row.creatorId)" slot="reference" icon="el-icon-link" title="发布文档" size="small" circle></el-button>
            <el-input v-model="url" placeholder="输入文档访问路径（可空）"></el-input>
            <el-button @click="publishDocWithUrl(url, scope)" type="primary" style="margin-top: 10px; width: 100%">发布</el-button>
          </el-popover>
        </div>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import {compressDate, compressText} from '@/utils/display'
import {deleteDocById, download, downloadFileToUser, getDocByUrl, publishDoc} from '@/api/document'

export default {
  name: 'DocumentList',
  props: {
    paginationLayout: {
      type: String,
      default: 'total, prev, pager, next'
    },
    projectId: {
      type: [String, Number]
    },
    defaultPageSize: {
      type: Number,
      default: 10
    }
  },
  data () {
    return {
      pageSize: this.defaultPageSize,
      currentPage: 1,
      tableLoading: false,
      url: undefined,
      visible: {
        publish: []
      }
    }
  },
  methods: {
    handleSizeChange (val) {
      this.pageSize = val
    },
    deleteDoc (row) {
      console.log('delete')
      deleteDocById(row.projectId, row.id).then(() => {
        this.init(row.projectId)
        this.$emit('onDelete', row)
      }).catch(error => {
        this.$notify.error(error)
      })
    },
    goPublishPage (row) {
      let path = this.$router.resolve('/document/' + row.url)
      this.$store.commit('SET_CURRENT_DOC_INFO', row)
      localStorage.setItem('CURRENT_DOC_INFO', JSON.stringify(row))
      window.open(path.href, '_blank')
    },
    init (projectId) {
      if (projectId) {
        this.tableLoading = true
        this.$store.dispatch('LoadDocuments', projectId).then(() => {
          setTimeout(() => {
            this.tableLoading = false
          }, 400)
        }).catch(() => {
          setTimeout(() => {
            this.tableLoading = false
          }, 400)
        })
      } else {
        this.$notify.error('项目ID为空')
      }
    },
    compress (text, length = 6) {
      return compressText(text, length)
    },
    compressDate (value) {
      return compressDate(value)
    },
    rowSelect (row) {
      this.$store.commit('SET_CURRENT_DOC', row.id)
      this.$store.dispatch('LoadDocumentLogs', row.id)
      this.$emit('onRowChange', row)
    },
    editDoc (row) {
      this.$emit('onEdit', row)
    },
    downloadDoc (row) {
      if (row.url) {
        getDocByUrl(row.url).then(res => {
          if (res.msg) {
            this.$notify.error(res.msg)
            return
          }
          downloadFileToUser(res, row.name)
        }).catch(error => {
          this.$notify.error(error)
        })
      } else {
        download(row.projectId, row.id).then(res => {
          if (res.msg) {
            this.$notify.error(res.msg)
            return
          }
          downloadFileToUser(res, row.name)
        }).catch(error => {
          this.$notify.error(error)
        })
      }
    },
    publishDocWithUrl (url, scope) {
      let row = scope.row
      publishDoc({
        projectId: row.projectId,
        docId: row.id,
        url: url
      }).then(res => {
        this.$notify.success('发布成功：' + res.data.publishUrl)
        this.$store.dispatch('LoadDocuments', row.projectId)
        this.$store.commit('SET_DOCUMENT_LOGS', [])
        this.$set(this.visible.publish, scope.$index, false)
        this.url = undefined
      }).catch(error => {
        this.$notify.error(error)
      })
    },
    hasPermission (creatorId) {
      if (this.isCurrentProjectCreator) return true
      return creatorId === this.$store.getters.currentUserId
    }
  },
  mounted () {
    if (this.documents.length === 0) {
      this.init(this.projectId)
    }
  },
  computed: {
    documents () {
      return this.$store.getters.documents
    },
    tableData () {
      return this.documents.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
    },
    isCurrentProjectCreator () {
      if (!this.$store.getters.currentProjectData) {
        return false
      }
      return this.$store.getters.currentProjectData.creatorId === this.$store.getters.currentUserId
    }
  },
  watch: {
    projectId: {
      handler (newVal, oldVal) {
        this.projectId = newVal
        this.init(newVal)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  border: 0;
}
</style>
